package com.esunny.online.controller;

import com.esunny.online.domain.dto.ReturnStructure;
import com.esunny.online.domain.entity.User;
import com.esunny.online.service.UserService;
import com.esunny.online.util.ConstantUtil;
import com.esunny.online.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：李先生
 * @date ：Created in 2020/7/24 10:12
 * @description： 登录相关控制器
 * @modified By：
 * @version: 1.0$
 */
@Api(value = "登录相关控制器")
@Controller
public class LoginController {
    @Resource
    private UserService userService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 登录请求
     *
     * @param map 数据
     * @return JSON
     */
    @ApiOperation(value = "登录接口", notes = "基于用户名和密码进行登录")
    @ApiImplicitParam(paramType = "body", name = "map", value = "Map形式结合注解解析传入JSON", required = true, dataType = "Map")
    @ApiResponse(code = 400, message = "参数错误", response = ReturnStructure.class)
    @PostMapping("/login")
    @ResponseBody
    public ReturnStructure login(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        String method = "/login：";
        String username = "username";
        String password = "password";
        if (map == null || map.isEmpty()) {
            logger.warn(ConstantUtil.LOGGER_CONTROLLER_LOGIN + method + "用户名或密码为空");
            return new ReturnStructure(400, "用户名或密码为空");

        } else if (map.get(username) == null || map.get(password) == null
                || StringUtils.isBlank((String) map.get("username")) || StringUtils.isBlank((String) map.get("password"))) {

            logger.warn(ConstantUtil.LOGGER_CONTROLLER_LOGIN + method + "用户名或密码为空");
            return new ReturnStructure(400, "用户名或密码为空");

        } else {
            User user = userService.login(map);
            if (user == null) {
                logger.warn(ConstantUtil.LOGGER_CONTROLLER_LOGIN + method + "用户名或密码错误");
                return new ReturnStructure(400, "用户名或密码错误");
            } else {
                user.setPassword(" ");
                String ticket = JwtUtil.createJwt(user);
                Map<String, Object> data = new HashMap<>(5);
                data.put("ticket", ticket);
                data.put("keepalive", ConstantUtil.JWT_EXPIRE_SECOND);
                data.put("user", user);

                //cookie相关配置
                response.setHeader("Access-Control-Expose-Headers",
                        "Cache-Control,Content-Type,Expires,Pragma,Content-Language,Last-Modified,token");
                response.setHeader("ticket", ticket);
                Cookie cookie = new Cookie("ticket", ticket);
                cookie.setPath(contextPath);
                cookie.setMaxAge(ConstantUtil.JWT_EXPIRE_SECOND);
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.addCookie(cookie);
                logger.info("cookieName：" + cookie.getName());
                logger.info("cookieValue" + cookie.getValue());


                return new ReturnStructure(200, "登录成功", data);
            }
        }

    }
}
